package com.tl.common.api;

import java.util.Map;

import android.content.Context;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.tl.common.constant.NetConstant;
import com.tl.common.util.DebugUtil;
import com.tl.common.util.StringUtils;

public class NetAquery implements NetDao {

	Context mContext;
	AQuery mAquery;
	OnHttpReturnListener mListener;

	public NetAquery(Context context) {
		// TODO Auto-generated constructor stub
		mContext = context;
		mAquery = new AQuery(mContext);
	}

	@Override
	public void setOnHttpReturnListener(OnHttpReturnListener listener) {
		// TODO Auto-generated method stub
		this.mListener = listener;
	}

	@Override
	public void BeginHttp(String url, Map<String, Object> params,
			boolean isRefresh) {
		DebugUtil.println("链接:" + url);

		AjaxCallback<String> cb;
		cb = new AjaxCallback<String>();

		if (params != null && params.size() > 0) {
			// post方式
			if (isRefresh) {
				cb.url(url)
						.params(params)
						.type(String.class)
						.weakHandler(this, "GetReturn")
						.fileCache(true)
						.memCache(false)
						.refresh(isRefresh)
						.header("Content-Type",
								"application/json;charset=UTF-8");

			}

		} else {
			// get方式
			cb.url(url).type(String.class).weakHandler(this, "GetReturn")
					.fileCache(true).memCache(false).refresh(isRefresh)
					.header("Content-Type", "application/json;charset=UTF-8");

		}

		mAquery.ajax(cb);

	}

	public void GetReturn(String url, String json, AjaxStatus status) {
		String errorMessage = "";
		int state = NetConstant.NET_RETURN_SUCESS;

		if (status.getSource() == AjaxStatus.FILE) {
			DebugUtil.println("从文件缓存中获取数据");
		} else {
			DebugUtil.println("从网络中获取数据");
			if (status.getCode() < 0) {
				errorMessage = status.getMessage();
				state = NetConstant.NET_RETURN_NET_ERROR;
			}
		}

		if (StringUtils.isEmpty(json)) {
			errorMessage = "无数据返回";
			state = NetConstant.NET_RETURN_NULL;
		}

		if (mListener != null)
			mListener.onHttpReturn(json, state, errorMessage);

	}

}
